package cn.com.dashihui.api.radisysnc.inter.impl;

import java.util.concurrent.ArrayBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.dashihui.api.radisysnc.inter.IRequest;
import cn.com.dashihui.api.radisysnc.inter.IRequestAsyncProcessBiz;
import cn.com.dashihui.api.radisysnc.request.RequestQueue;
/**
 * ***********************************************
　 * <p>类名: RequestAsyncProcessBizImpl</p> 
　 * <p>描述: 异步处理请求,用于路由队列并把请求加入到队列中</p> 
　 * @author niufc 
　 * @date 2019年8月20日 
  * ************************************************
 */
public class ImplRequestAsyncProcessBiz implements IRequestAsyncProcessBiz  {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void process(IRequest request) {
		// 做请求的路由，根据goodsId路由到对应的队列
        ArrayBlockingQueue<IRequest> queue = getQueueByGoodsId(request.getGoodsId());
        try {
            queue.put(request);
        } catch (InterruptedException e) {
            logger.info("产品ID{}加入队列失败",request.getGoodsId(),e);
        }

	}

	@Override
	public void processOrderG(IRequest request) {
		// 做请求的路由，根据goodsId路由到对应的队列
        ArrayBlockingQueue<IRequest> queue = getQueueByOrderNum(request.getOrderNum());
        try {
            queue.put(request);
        } catch (InterruptedException e) {
            logger.info("产品ID{}加入队列失败",request.getOrderNum(),e);
        }
	}

    private ArrayBlockingQueue<IRequest> getQueueByGoodsId(Integer goodsId) {
        RequestQueue  requestQueue = RequestQueue.getInstance();
        String key = String.valueOf(goodsId);
        int hashcode;
        int hash = (key == null) ? 0 : (hashcode = key.hashCode())^(hashcode >>> 16);
        //对hashcode取摸
        int index = (requestQueue.getQueueSize()-1) & hash;
        return requestQueue.getQueueByIndex(index);
    }
    
    private ArrayBlockingQueue<IRequest> getQueueByOrderNum(String orderNum) {
        RequestQueue  requestQueue = RequestQueue.getInstance();
        String key = String.valueOf(orderNum);
        int hashcode;
        int hash = (key == null) ? 0 : (hashcode = key.hashCode())^(hashcode >>> 16);
        //对hashcode取摸
        int index = (requestQueue.getQueueSize()-1) & hash;
        return requestQueue.getQueueByIndex(index);
    }



}
